define(['moment'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', 'config',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, config) {
            $scope.init = function (machineList, type, feedback) {
                $scope.user_name = config.cache.name;
                $scope.shift_info = config.cache.shift_info;
                $scope.checkedgroup = true;
                $scope.equipment_no = $stateParams.data.machine.machine_no;
                $scope.equipment_name = $stateParams.data.machine.machine_name;
                $scope.group_user_list = [];
                $scope.OnWorkInfo_detail = []; //人员清单
                $scope.tmpOnWorkInfo = {};//人员上工原因
                $scope.need_work_reason = (config.cache.sys_parameter.EmployeeWorkReason == '1' || config.cache.sys_parameter.EmployeeWorkReason == '3'); //上工是否需輸入原因
                $scope.errormsg = ""; //人员技能检核报错信息
                $scope.errormsgfinal = "";
                $scope.tmpUser_no = ''
                //$scope.machineList = $stateParams.data.machine;
                $scope.machineList = []
                $scope.machineList = $stateParams.data.machines
                beforeShown()


            };

            //扫描
            $scope.QRCodeScanner = function () {
                $scope.$root.OpenScanner({
                    after: function (result) {
                        $scope.tmpUser_no = result.text;
                    },
                    exception: function () {
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation: 'portrait'
                });
            };

            function beforeShown() {
                $scope.machineList.forEach(function (item) {
                    item.employee_work_detail.forEach(function (workitem) {
                        var min_parameter_value = 0;
                        var tempitem = $filter('filter')($scope.OnWorkInfo_detail, { user_no: workitem.employee_no }, true);
                        if (tempitem && tempitem.length > 0) {
                            if (tempitem[0].parameter_value >= item.parameter_value) {
                                min_parameter_value = item.parameter_value;
                            }
                            else {
                                min_parameter_value = tempitem[0].parameter_value;
                            }
                            $scope.OnWorkInfo_detail.forEach(function (detail) {
                                if (detail.user_no == tempitem[0].user_no) {
                                    detail.parameter_value = min_parameter_value;
                                }
                            })
                        }
                        else {
                            var tmpUser = {
                                user_no: workitem.employee_no,
                                user_name: workitem.employee_name,
                                parameter_value: workitem.parameter_value
                            };
                            $scope.OnWorkInfo_detail.push(tmpUser);
                        }
                    })
                    if (item.CategoryLeader && item.CategoryLeader.length > 0) {
                        for (var i = 0; i < item.CategoryLeader.length; i++) {
                            if ($scope.group_user_list.indexOf(item.CategoryLeader[i]) <= -1) {
                                $scope.group_user_list.push(item.CategoryLeader[i]);
                            }
                        }
                    }


                })
                try {
                    document.getElementById('tmpEmp_no').focus();
                } catch (e) { console.error(e); }
            }


            function beforeEmpWorkSet(dialog, callback) {
                if ($scope.need_work_reason && !$scope.tmpOnWorkInfo.reason_no) {
                    loadEmpWorkReason('', function (selectItem) {
                        $scope.tmpOnWorkInfo.reason_no = selectItem.page_no;
                        $scope.tmpOnWorkInfo.reason_name = selectItem.page_name;
                        if (callback)
                            callback();
                    });
                } else {
                    if (callback)
                        callback();
                }
            }
            // 人員原因基本資料取得
            function loadEmpWorkReason(reason_no, callback) {
                $MMWService.pageNumberInfoGet({
                    page_mode: '35',
                    query_condition_info: [
                        { column_name: 'REASONTYPE', query_mode: '0', value: '0', merge_condition_model: 'AND' },
                        { column_name: 'ISSUESTATE', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                    ]
                }, function (items) {
                    if (items && items.length > 0) {
                        $rootScope.showSelect({
                            label: function (item) {
                                return item.page_name + '(' + item.page_no + ')';
                            },
                            title: $filter('translate')('home.plz_select_online_reason'),
                            code: 'page_no',
                            selectCode: reason_no || '',
                            list: items,
                            confirm: function (selectItem, radio_dialog) {
                                radio_dialog.hide();
                                if (callback)
                                    callback(selectItem);
                            }
                        });
                    } else {
                        $rootScope.showAlert($filter('translate')('home.msg.online_reason_empty'));
                    }
                });
            }
            function addWorkItem(dialog, machine, employeewrokset) {
                var msg = '';

                if ($scope.need_work_reason && !$scope.tmpOnWorkInfo.reason_no) {
                    msg += $filter('translate')('moblie13.showAlert.column5') + "<br>";
                }

                if (msg == '') {
                    $scope.OnWorkInfo_detail.forEach(function (item) {
                        employeewrokset.push({
                            machine_no: machine.machine_no,
                            machine_name: machine.machine_name,
                            employee_no: item.user_no,
                            parameter_value: item.parameter_value == "" ? 0 : item.parameter_value,
                            work_mode: 'U',
                            work_datetime: new Date(),
                            reason_no: $scope.tmpOnWorkInfo.reason_no || ''
                        });
                    })

                }
                return msg;
            }
            //上工
            function empWorkSet(dialog) {
                var msg = '';
                var content = {
                    employeewrokset: []
                };
                $scope.machineList.forEach(function (machine) {
                    msg += addWorkItem($scope.OnWorkInfo_detail, machine, content.employeewrokset);
                });
                if (msg == '') {
                    if (content.employeewrokset.length > 0) {
                        employee_wrok_set_Imp(dialog, content);
                    } else {
                        $rootScope.showToast($filter('translate')('moblie13.msg.user_list_empty'));
                    }
                } else {
                    $rootScope.showAlert(msg);
                }
            }

            $scope.back = function () {
                $rootScope.changeProgram('home', true);
            };
            $scope.deleteEmployee = function (index, item) {
                $scope.OnWorkInfo_detail.splice(index, 1);
            };
            $scope.searchUser = function (event) {
                if (!event || event.keyCode == 13) {
                    if ($scope.tmpUser_no != '') {
                        if ($scope.checkedgroup) {
                            var content = {
                                type: "group",
                                user_no: $scope.tmpUser_no
                            };
                        }
                        else {
                            var content = {
                                type: "user",
                                user_no: $scope.tmpUser_no
                            };
                        }
                        //dialog.addUser(1);
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.usr_report_group_get',
                            content: content,
                            success: function (data) {
                                if (data.group_user_list && data.group_user_list.length > 0) {
                                    for (var i = 0; i < data.group_user_list.length; i++) {
                                        if ($scope.group_user_list.indexOf(data.group_user_list[i]) <= -1) {
                                            $scope.group_user_list.push(data.group_user_list[i]);
                                        }
                                    }
                                }

                                addUser(data.report_group_detail);
                            },
                            error: function (data) {
                                $rootScope.showAlert(data.Message, function () {
                                    document.getElementById('tmpEmp_no').focus();
                                });
                            }
                        });
                    } else {
                        $rootScope.showAlert($filter('translate')('mobile13.msg.input_labor_empty'), function () {
                            document.getElementById('tmpEmp_no').focus();
                        });
                    }
                }
            };


            function addUser(data) {
                if ($scope.checkedgroup) {
                    if (data && data.length > 0) {
                        if (data.length == 1) {
                            data[0].user_detail.forEach(function (item) {
                                var min_parameter_value = 0;
                                var temp = $filter('filter')($scope.OnWorkInfo_detail, { user_no: item.user_no }, true);
                                if (temp && temp.length > 0) {
                                    if (temp[0].parameter_value >= item.parameter_value) {
                                        min_parameter_value = item.parameter_value;
                                    }
                                    else {
                                        min_parameter_value = temp[0].parameter_value;
                                    }
                                    $scope.OnWorkInfo_detail.forEach(function (detail) {
                                        if (detail.user_no == temp[0].user_no) {
                                            detail.parameter_value = min_parameter_value;
                                        }
                                    })
                                }
                                else {
                                    var tmpUser = {
                                        user_no: item.user_no,
                                        user_name: item.user_name,
                                        parameter_value: item.parameter_value
                                    };
                                    $scope.OnWorkInfo_detail.push(tmpUser);
                                }
                            })
                        }
                        else {
                            $rootScope.showSelect({
                                label: 'category',
                                code: 'category',
                                //selectCode: item.responseprocess,
                                list: data,
                                confirm: function (detail, radioDialog) {
                                    radioDialog.hide();
                                    detail.user_detail.forEach(function (item) {
                                        var min_parameter_value = 0;
                                        var temp = $filter('filter')($scope.OnWorkInfo_detail, { user_no: item.user_no }, true);
                                        if (temp && temp.length > 0) {
                                            if (temp[0].parameter_value >= item.parameter_value) {
                                                min_parameter_value = item.parameter_value;
                                            }
                                            else {
                                                min_parameter_value = temp[0].parameter_value;
                                            }
                                            $scope.OnWorkInfo_detail.forEach(function (detail) {
                                                if (detail.user_no == temp[0].user_no) {
                                                    detail.parameter_value = min_parameter_value;
                                                }
                                            })
                                        }
                                        else {
                                            var tmpUser = {
                                                user_no: item.user_no,
                                                user_name: item.user_name,
                                                parameter_value: item.parameter_value
                                            };
                                            $scope.OnWorkInfo_detail.push(tmpUser);
                                        }
                                    })
                                }
                            });
                            //$rootScope.showQueryList({
                            //    pageRecord: 50,
                            //    key: 'category',
                            //    header: [
                            //        { label: $filter('translate')('B0231.title'), code: 'category' }
                            //    ],
                            //    query: function (conditions, feedback) {
                            //        feedback(data);
                            //    },
                            //    confirm: function (detail, radioDialog) {
                            //        radioDialog.hide();
                            //        detail.user_detail.forEach(function (item) {
                            //            dialog.OnWorkInfo_detail.push(item);
                            //        })
                            //    }
                            //});
                        }
                    }
                }
                else {
                    if (data && data.length > 0) {
                        if (data[0].user_detail.length > 0) {
                            var min_parameter_value = 0;
                            var temp = $filter('filter')($scope.OnWorkInfo_detail, { user_no: data[0].user_detail[0].user_no }, true);
                            if (temp && temp.length > 0) {
                                if (temp[0].parameter_value >= data[0].user_detail[0].parameter_value) {
                                    min_parameter_value = data[0].user_detail[0].parameter_value;
                                }
                                else {
                                    min_parameter_value = temp[0].parameter_value;
                                }
                                $scope.OnWorkInfo_detail.forEach(function (detail) {
                                    if (detail.user_no == temp[0].user_no) {
                                        detail.parameter_value = min_parameter_value;
                                    }
                                })
                            }
                            else {
                                var tmpUser = {
                                    user_no: data[0].user_detail[0].user_no,
                                    user_name: data[0].user_detail[0].user_name,
                                    parameter_value: data[0].user_detail[0].parameter_value
                                };
                                $scope.OnWorkInfo_detail.push(tmpUser);
                            }
                        }
                    }

                }
            }

            $scope.changeParameter = function () {
                $mdDialog.dialog(
                     'module/moduleMobile/program/mobile13/CheckPermission_tmp.html',
                     function (dialogcheck) {
                         return {
                             confirm: function () {
                                 if (dialogcheck.Account && dialogcheck.Password) {
                                     //检核权限
                                     if ($scope.group_user_list.indexOf(dialogcheck.Account) > -1) {
                                         $MMWService.sendToServer({
                                             uri: 'ServicesSTD.Module_SYS.user_permissions_info_get_json',
                                             content: {
                                                 login_employee_no: dialogcheck.Account,
                                                 login_employee_password: dialogcheck.Password
                                             },
                                             success: function (data) {
                                                 dialogcheck.hide();
                                                 var xlist = document.getElementsByClassName("checktype");
                                                 if (xlist && xlist.length > 0) {
                                                     for (var i = 0; i < xlist.length; i++) {
                                                         xlist[i].readOnly = false;
                                                     }
                                                 };
                                             },
                                             error: function () {
                                                 $rootScope.showAlert($filter('translate')('mobile13.msg.password_error'), function () {
                                                     document.getElementById('groupuser_password').focus();
                                                 });
                                             }
                                         });

                                     }
                                     else {
                                         $rootScope.showAlert($filter('translate')('mobile13.msg.no_permission'), function () {
                                             document.getElementById('groupuser_account').focus();
                                         });
                                     }


                                 }


                             },
                             back: function () {
                                 dialogcheck.hide();
                             }
                         }
                     })
            }
            $scope.groupCheck = function () {
                $scope.checkedgroup = !$scope.checkedgroup
            }
            $scope.confirm = function () {
                var work_mode = 'U';//machine.employee_status;
                var content = {
                    work_mode: work_mode,
                    employeewrokset: [{
                        machine_no: $scope.equipment_no,
                        machine_name: $scope.equipment_name,
                        employee_no: config.cache.account,
                        work_mode: work_mode,
                        work_datetime: new Date(),
                        reason_no: ''
                    }]
                };
                $scope.errormsg = ""; //人员技能检核报错信息
                $scope.errormsgfinal = "";
                beforeEmpWorkSet(content, function () {
                    empWorkSet(content);
                });
            }

            // 檢查是否有設定技能
            function checkNeedInspetSkill(machine, type, feedback, secondfeedback) {
                var page_mode = '';
                var query_condition_info = [];

                if (type === 0) {
                    page_mode = '40-1'; //設備設定技能取得
                    query_condition_info = [
                        { column_name: 't.EQUIPMENTNO', query_mode: '0', value: machine.machine_no, merge_condition_model: 'AND' }
                    ];
                } else {
                    page_mode = '40-2'; //工位設定技能取得
                    query_condition_info = [
                        { column_name: 't.PDLINENO', query_mode: '0', value: '', merge_condition_model: 'AND' },
                        { column_name: 't.POSITIONNO', query_mode: '0', value: '', merge_condition_model: 'AND' }
                    ];
                }

                $MMWService.pageNumberInfoGet({
                    page_mode: page_mode,
                    query_condition_info: query_condition_info
                }, function (items) {
                    if (items && items.length > 0) {
                        // 有設定技能，執行技能檢驗邏輯
                        if (feedback)
                            feedback();
                    } else {
                        // 不需檢驗人員技能，繼續執行上工逻辑
                        if (secondfeedback)
                            secondfeedback();
                    }
                });
            }

            // 人員技能檢驗資訊取得
            function userSkillInspectInfoGet(content, machine, feedback) {
                $MMWService.sendToSMESServer({
                    uri: 'tcSMES_skill.clsSMES.required_skills_info_get',
                    content: content,
                    success: function (data) {
                        if (data.error_msg && data.msg != "") {
                            var msglist = data.error_msg.split(",");
                            msglist.forEach(function (item) {
                                var detail = item.split("-");
                                $scope.errormsg = $scope.errormsg + detail[0] + "在" + machine.machine_name + "上" + detail[1] + "不合格,";
                            });
                        }
                        if (feedback)
                            feedback();

                    }
                });
            }

            // 人員技能檢驗
            function inspectUserSkill(inspectInfo, dialog, feedback) {
                if (inspectInfo && inspectInfo.length > 0) {
                    var machineInfo = inspectInfo.shift();
                    var typevalue = "";
                    var userlist = [];
                    //if (parent == 'B0214' || parent == 'B0215' || parent == 'mobile_home') {
                        typevalue = 0;   // 0: 機台
                    //} else if (parent == 'E01') {
                    //    typevalue = 1;   // 1: 工位
                    //}
                    $scope.OnWorkInfo_detail.forEach(function (user) {
                        userlist.push(user.user_no);
                    });
                    var content = {
                        user_no_list: userlist,
                        type: typevalue  // 0: 機台, 1: 工位
                    };
                    if (typevalue == 0) {  // 機台查詢條件 = 機台編號
                        content.id = machineInfo.machine_no;
                    } else if (typevalue == 1) {    // 工位機查詢條件 = 工位機編號+區域編號+作業站編號
                        content.id = machineInfo.machine_no;
                        content.parameter1 = '',
                        content.parameter2 = '';
                    }

                    if (machineInfo ) { 
                        checkNeedInspetSkill(machineInfo, typevalue, function () {
                            userSkillInspectInfoGet(content, machineInfo, function () {
                                inspectUserSkill(inspectInfo, dialog, feedback);
                            });
                        }, function () {
                            inspectUserSkill(inspectInfo, dialog, feedback);
                        });
                    } else {
                        if (feedback)
                            feedback();
                    }
                } else {
                    if (feedback)
                        feedback();
                }
            }

            function employee_wrok_set_Imp(dialog, content) {
                //var inspectInfo = {
                //    parent: "mobile_home",
                //    op_no: '',
                //    area_no: '',
                //    user_no: $scope.tmpOnWorkInfo.employee_no,
                //    user_name: $scope.tmpOnWorkInfo.employee_name,
                //    user_title: $scope.tmpOnWorkInfo.user_title,
                //    releaser_verified: false,
                //    employeewrokset: angular.extend([], content.employeewrokset)
                //};
                //inspectUserSkill(inspectInfo, function () {
                //employee_wrok_set(dialog, content);
                //});

                var tempmachinelist = JSON.parse(JSON.stringify($scope.machineList));
                inspectUserSkill(tempmachinelist, dialog, function () {
                    if ($scope.errormsg != "") {
                        $scope.errormsgfinal = $scope.errormsg.substring(0, $scope.errormsg.length - 1);
                        $scope.$root.showAlert($scope.errormsgfinal);
                    }
                    else {
                        employee_wrok_set(dialog, content);
                    }
                });
            }


            function employee_wrok_set(dialog, content) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.usr_report_group_process',
                    content: content,
                    success: function (data) {
                        $rootScope.showToast($filter('translate')('mobile13.showAlert.column1'));
                        $rootScope.changeProgram('home', true);
                        //if (feedback)
                        //    feedback();
                    }
                });
            }


           
        }
    ];
});
